package io.github.junxworks.qt.modules.mm.engine.handlers;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.github.junxworks.junx.event.EventChannel;
import io.github.junxworks.junx.event.EventChannelHandler;
import io.github.junxworks.junx.event.EventContext;
import io.github.junxworks.qt.config.Params;
import io.github.junxworks.qt.config.Topics;
import io.github.junxworks.qt.modules.mm.engine.DataContext;
import io.github.junxworks.qt.modules.mm.engine.Datastream;
import io.github.junxworks.qt.modules.mm.engine.Fielder;
import io.github.junxworks.qt.modules.mm.engine.StreamDataBundle;
import io.github.junxworks.qt.modules.mm.vo.FieldVo;

@Component
public class FieldInitHandler implements EventChannelHandler {

	@Autowired
	private Fielder fielder;

	@Override
	public void handleEvent(EventContext event, EventChannel channel) throws Exception {
		final DataContext data = event.getData(DataContext.class, Params.DATA_CONTEXT);
		if (data.isDone()) {
			return;
		}
		try {
			List<StreamDataBundle> dataObj = data.getBundle();
			if (dataObj.isEmpty()) {
				data.done(); //没有数据直接闭掉
			}
			dataObj.forEach(s -> {
				if (s.getRows().isEmpty()) {
					data.done();
				}
			});
			if (!data.isDone()) {
				dataObj.forEach(d -> {
					String dsName = d.getDataStreamName();
					Datastream ds = data.getExeContext().getDataStream(dsName);
					List<Map<String, Object>> rows = d.getRows();
					rows.forEach(row -> {
						//可能会存在多条记录，要把字段翻译结果动态判断，如果只有一个值和多个值做区别
						row.entrySet().forEach(en -> {
							FieldVo field = ds.getFieldModel(en.getKey());
							if (field != null) {
								data.addFieldData(dsName, field.getInnerCName(), fielder.translateField(dsName, field, en.getValue()));
							}
						});
					});
					
				});

				String topic = Topics.STAT_SYNC;
				if (data.isStock()) {
					topic = Topics.STAT_ASYNC; //股票本身的流才走异步统计
				}
				EventContext ctx = new EventContext(topic);
				ctx.setData(Params.DATA_CONTEXT, data);
				channel.publish(topic, ctx);
			}
		} catch (Throwable e) {
			data.setException(e);
		}
	}

}
